﻿using Avalonia.Extensions.Controls;
using Bilibili.Common.Log;
using Bilibili.Model.Channel;
using Bilibili.Model.Dynamic;
using Bilibili.WebClient.Api;
using DynamicData;
using ReactiveUI;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;

namespace Avalonia.BiliBili.ViewModels
{
    public sealed class DynamicTopicViewModel : ViewModelBase
    {
        private int page = 1;
        private DynamicClient Client { get; }
        public ChannelClient Channel { get; }
        private ObservableCollection<DynamicCards> cards = [];
        public ObservableCollection<DynamicCards> DynamicCards
        {
            get => cards;
            private set => this.RaiseAndSetIfChanged(ref cards, value);
        }
        private ObservableCollection<ChannelFeed> channelFeeds = [];
        public ObservableCollection<ChannelFeed> ChannelFeeds
        {
            get => channelFeeds;
            private set => this.RaiseAndSetIfChanged(ref channelFeeds, value);
        }
        public DynamicTopicViewModel()
        {
            Client = new DynamicClient();
            Channel = new ChannelClient();
        }
        public async Task LoadDymamic(string tag)
        {
            try
            {
                var result = await Client.LoadDymamic(tag, DynamicCards.LastOrDefault()?.Dynamic_Id);
                if (result.Success)
                {
                    var dynamicModel = result.Data;
                    if (dynamicModel.code == 0)
                    {
                        if (dynamicModel.data.cards == null)
                            PopupToast.Show("没有更多动态了");
                        else
                        {
                            var cards = dynamicModel.data.cards.Where(x => x.Desc.Type != 32);
                            var index = DynamicCards.Count == 1 ? 0 : DynamicCards.Count - 2;
                            DynamicCards.AddOrInsertRange(cards, index);
                        }
                    }
                    else
                        PopupToast.Show(dynamicModel.msg);
                }
                else
                    PopupToast.Show(result.Message);
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("LoadDymamic", ex);
            }
        }
        public async Task LoadData(string id, string name)
        {
            try
            {
                var data = await Channel.GetChannelFeeds(id, name, page);
                if (data.Success && data.Data.Count != 0)
                {
                    ChannelFeeds.AddRange(data.Data);
                    page++;
                }
                else
                    PopupToast.Show(data.Message);
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("LoadData", ex);
            }
        }
    }
}